import { h, unref, defineComponent, computed, Ref } from "vue";
import { ElOption, ElSelect } from "element-plus";
import usePage from "@/hooks/usePage";
import { isFunction } from "lodash-es";

import type { TOptions } from "../type";

type TProps = {
  valueKey?: string;
  labelKey?: string;
  options?: TOptions | Ref<TOptions>;

  render?: any;
  renderContent?: (e: any) => any;

  fetchUrl?: string | Ref<string>;
  fetchOptions?: any;
  optionPropRender?: (item: any) => TOptions;
};

const ProSelect = defineComponent(
  (props: TProps) => {
    const { list } = usePage(unref(props.fetchUrl) || "", {
      ...props.fetchOptions,
      immediate: !!unref(props.fetchUrl),
    });

    const optionsNode = computed(() => {
      let {
        options,
        fetchUrl,
        valueKey = "value",
        labelKey = "label",
        render,
        renderContent,
        optionPropRender,
      } = props;

      const _options = unref(fetchUrl)
        ? (unref(list) as any)
        : unref(options) ?? [];

      return _options?.map((item: any) => {
        const optionProps = isFunction(optionPropRender)
          ? optionPropRender(item)
          : { value: item[valueKey], label: item[labelKey] };

        return h(
          ElOption,
          optionProps as { label: string; value: string | number },
          () =>
            render
              ? h(render, { config: item })
              : renderContent?.(item) ?? item.label ?? item.value
        );
      });
    });

    return () => h(ElSelect, () => optionsNode.value);
  },
  {
    props: [
      "valueKey",
      "labelKey",
      "options",
      "render",
      "renderContent",
      "fetchUrl",
      "fetchOptions",
      "optionPropRender",
    ],
  }
);

export default ProSelect;
